/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fsd.semana3.aula.echothread;

import java.net.Socket;
import java.nio.ByteBuffer;

/**
 *
 * @author nfsa
 */
public class EchoThread extends Thread {

    private Socket socket;

    public EchoThread (Socket _socket) throws Exception
    {
        socket = _socket;
    }

    @Override
    public void run() {
        while (!socket.isClosed())
        {
            ByteBuffer buf = ByteBuffer.allocate(256);
            readLine(buf);
            writeLine(buf);
        }
    }

    public void readLine (ByteBuffer buf)
    {
        try
        {
            boolean proceed = true;
            while (proceed) {
                int val = socket.getInputStream().read();
                proceed = ((char) val != '\n' && val != -1);
                if (val != -1) {
                    buf.put((byte) val);
                }
                else {
                    socket.close();
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void writeLine (ByteBuffer buf)
    {
        try
        {
            if (!socket.isClosed()) {
                socket.getOutputStream().write(buf.array());
                socket.getOutputStream().flush();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
